package com.inteceptor;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AuthInteceptor implements HandlerInterceptor {

	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
			Exception arg3) throws Exception {
		// TODO Auto-generated method stub

	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
			ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub

	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
			throws Exception {

		String[] noFilters = new String[] {  "user/doCommentAction", "user/login", "user/register", "user/checkname",
				"user/checkemail", "user/doAction", "user/minilogin","upload/images" };
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":"
				+ request.getServerPort() + path + "/";
		StringBuffer url = request.getRequestURL();
		String uri = request.getRequestURI();
		for (int i = 0; i < noFilters.length; i++) {
			if (uri.contains(noFilters[i])) {
				return true;
			}
		}
		HttpSession session = request.getSession(true);
		Object isLogin = session.getAttribute("isLogin");
		if (isLogin == null) {
			response.sendRedirect(basePath + "user/login.html?redirect="
					+ URLEncoder.encode(url.toString(), "UTF-8"));
			return false;
		}
		else if ((Boolean) isLogin == false) {
			response.sendRedirect(basePath + "user/login.html?redirect="
					+ URLEncoder.encode(url.toString(), "UTF-8"));
			return false;
		}
		else {
			return true;
		}

	}

}
